#include "mysettings.h"
#include <QNetworkProxy>
#include <parser.h>
#include <serializer.h>
#include <qobjecthelper.h>

MySettings::MySettings()
{
    SettingsFile = dataPath("settings.json");
    loadSettings();
}

QString MySettings::dataPath(const QString &file)
{
    QString dir = QDir::homePath()+"/.mySpaces";
    if(!QFile::exists(dir))
    {
        QDir qdir;
        qdir.mkpath(dir);
    }
    return dir+"/"+file;
}

void MySettings::loadSettings()
{
    QFile jsonfile(SettingsFile);
    jsonfile.open(QIODevice::ReadOnly);

    settings.setDownloadPath("");
    settings.setWindowMax(false);
    settings.setWindowX(0);
    settings.setWindowY(0);
    settings.setWindowH(400);
    settings.setWindowW(550);
    settings.setProxyEnable(false);

    QJson::Parser parser;
    bool ok;
    QVariant result = parser.parse( jsonfile.readAll(), &ok );
    if (!ok)
    {
        qFatal("An error occurred during parsing settings file.");
        exit (1);
    }
    jsonfile.close();
    QJson::QObjectHelper::qvariant2qobject(result.toMap(), &settings);
}

void MySettings::refresh()
{
    loadSettings();
}

void MySettings::save()
{
    QVariantMap variant = QJson::QObjectHelper::qobject2qvariant(&settings);
    QJson::Serializer serializer;
    const QByteArray serialized = serializer.serialize( variant);
    QFile savefile(SettingsFile);
    savefile.open(QIODevice::WriteOnly);
    savefile.write(serialized);
    savefile.close();
}

void MySettings::applyProxySettings()
{
    QNetworkProxy proxy;
    if(settings.ProxyEnable())
    {
        proxy.setType(QNetworkProxy::HttpProxy);
        proxy.setHostName(settings.ProxyHost());
        proxy.setPort(quint16(settings.ProxyPort()));
        proxy.setUser(settings.ProxyUser());
        proxy.setPassword(settings.ProxyPass());
    }
    else
    {
        proxy.setType(QNetworkProxy::NoProxy);
    }
    QNetworkProxy::setApplicationProxy(proxy);
}

MySettings::~MySettings()
{
    save();
}
